<template>
  <div>
    <n-card :bordered="false" class="fromCard">
      <BasicForm
        @register="register"
        :Toption="userStatus"
        @submit="handleSubmit"
        @reset="handleReset"
      >
        <template #statusSlot="{ model, field }">
          <n-input v-model:value="model[field]" />
        </template>
      </BasicForm>
    </n-card>
    <n-card :bordered="false" class="tableCard">
      <BasicTable
        :bordered="false"
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="actionRef"
        :actionColumn="actionColumn"
        :scroll-x="1090"
      >
        <template #tableTitle>
          <n-button type="primary" @click="addInfo" :disabled="!authority.includes('role_add')">
            <template #icon>
              <n-icon>
                <PlusOutlined />
              </n-icon>
            </template>
            新建
          </n-button>
        </template>
      </BasicTable>
    </n-card>
    <!-- 添加操作 -->
    <n-modal :show="addModal">
      <n-card style="width: 1000px" title="新增角色" size="huge" :bordered="false">
        <n-form
          :label-width="80"
          :model="addRole"
          :rules="rules"
          size="medium"
          ref="formRef"
          label-placement="left"
          label-align="left"
        >
          <n-grid :cols="2" :x-gap="28" style="margin-bottom: 20px">
            <n-gi span="1">
              <n-form-item :span="1" label="角色名称" path="name">
                <n-input placeholder="请输入角色名称" v-model:value="addRole.name" maxlength="30" />
              </n-form-item>
            </n-gi>
            <n-gi span="1">
              <n-form-item :span="1" label="角色描述" path="desc">
                <n-input placeholder="角色描述" v-model:value="addRole.desc" maxlength="300" />
              </n-form-item>
            </n-gi>
          </n-grid>
          <n-grid :cols="2" :x-gap="28" style="margin-bottom: 20px">
            <n-gi span="1">
              <n-form-item :span="1" label="角色代码" path="code">
                <n-input placeholder="请输入角色代码" v-model:value="addRole.code" maxlength="30" />
              </n-form-item>
            </n-gi>
            <n-gi span="1">
              <n-form-item :span="1" label="角色状态" path="status">
                <n-select
                  placeholder="请选择角色状态"
                  :options="roleStatelOptions"
                  v-model:value="addRole.status"
                />
              </n-form-item>
            </n-gi>
          </n-grid>
        </n-form>
        <template #action>
          <n-space justify="end">
            <n-button type="info" :loading="formBtnLoading" @click="addFrom">确定</n-button>
            <n-button @click="() => (addModal = false)">取消</n-button>
          </n-space>
        </template>
      </n-card>
    </n-modal>
    <!-- 编辑操作 -->
    <n-modal :show="editModal">
      <n-card style="width: 1000px" title="编辑用户" size="huge" :bordered="false">
        <n-form
          :label-width="80"
          :rules="rules"
          size="medium"
          ref="formRef"
          label-placement="left"
          label-align="left"
          :modal="updateRole"
        >
          <n-grid :cols="2" :x-gap="28" style="margin-bottom: 20px">
            <n-gi span="1">
              <n-form-item label="角色名称" path="name">
                <n-input v-model:value="updateRole.name" maxlength="30" />
              </n-form-item>
            </n-gi>
            <n-gi span="1">
              <n-form-item label="角色描述" path="desc">
                <n-input v-model:value="updateRole.desc" maxlength="300" />
              </n-form-item>
            </n-gi>
          </n-grid>
          <n-grid :cols="2" :x-gap="28" style="margin-bottom: 20px">
            <n-gi span="1">
              <n-form-item :span="1" label="角色代码" path="code">
                <n-input v-model:value="updateRole.code" maxlength="30" />
              </n-form-item>
            </n-gi>
            <n-gi span="1">
              <n-form-item :span="1" label="角色状态" path="status">
                <n-select
                  placeholder="请选择角色状态"
                  :options="roleStatelOptions"
                  v-model:value="updateRole.status"
                />
              </n-form-item>
            </n-gi>
          </n-grid>
        </n-form>
        <template #action>
          <n-space justify="end">
            <n-button
              type="info"
              :loading="formBtnLoading"
              @click="editFrom"
              style="background-color: #2d8cf0; color: #fff"
              >确定</n-button
            >
            <n-button @click="() => (editModal = false)">取消</n-button>
          </n-space>
        </template>
      </n-card>
    </n-modal>
    <!-- 查看操作 -->
    <n-modal :show="viewModal">
      <n-card style="width: 1000px" title="用户详情" size="huge" :bordered="false">
        <n-form
          :label-width="80"
          :rules="rules"
          :model="viewRole"
          size="medium"
          ref="formRef"
          label-placement="left"
          label-align="left"
        >
          <n-grid :cols="2" :x-gap="28" style="margin-bottom: 20px">
            <n-gi span="1">
              <n-form-item label="角色名称">
                <n-input disabled v-model:value="viewRole.name" />
              </n-form-item>
            </n-gi>
            <n-gi span="1">
              <n-form-item label="角色描述">
                <n-input disabled v-model:value="viewRole.desc" />
              </n-form-item>
            </n-gi>
          </n-grid>
          <n-grid :cols="2" :x-gap="28" style="margin-bottom: 20px">
            <n-gi span="1">
              <n-form-item :span="1" label="角色代码">
                <n-input disabled v-model:value="viewRole.code" />
              </n-form-item>
            </n-gi>
            <n-gi span="1">
              <n-form-item :span="1" label="角色状态">
                <n-select placeholder="请选择" v-model:value="viewRole.status" disabled> </n-select>
              </n-form-item>
            </n-gi>
          </n-grid>
        </n-form>
        <template #action>
          <n-space justify="end">
            <n-button
              @click="() => (viewModal = false)"
              style="background-color: #2d8cf0; color: #fff"
              >确认</n-button
            >
          </n-space>
        </template>
      </n-card>
    </n-modal>
    <!-- 分配权限 -->
    <n-modal :show="assignModal">
      <n-card
        style="width: 400px; height: 600px;"
        title="分配权限"
        size="huge"
        :bordered="false"
      >
        <n-form
          :label-width="80"
          :rules="rules"
          size="medium"
          ref="formRef"
          label-placement="left"
          label-align="left"
          :modal="assignInfoTree"
        >
          <n-card
            style="width: 350px; height: 400px; overflow: auto"
            size="small"
            :bordered="false"
          >
            <n-tree
              block-line
              checkable
              :data="assignInfoTree"
              @update:checked-keys="updateCheckedKeys"
              :default-checked-keys="defaultCheckedKeys"
            />
          </n-card>
        </n-form>

        <template #action>
          <n-space justify="end">
            <n-button type="info" :loading="formBtnLoading" @click="assignConfirm">确定</n-button>
            <n-button @click="() => (assignModal = false)">取消</n-button>
          </n-space>
        </template>
      </n-card>
    </n-modal>
    <!-- 删除操作 -->
    <n-modal
      v-model:show="delModal"
      :mask-closable="false"
      preset="dialog"
      title="确认"
      @positive-click="deletConfirm"
      @negative-click="deletCancel"
    >
      <h3 style="font-size: 15px; margin-top: 10px; margin-bottom: 10px">你确定要删除这条信息吗</h3>
      <n-space justify="end">
        <n-button @click="deletConfirm" style="background-color: #2d8cf0; color: #fff"
          >确认</n-button
        >
        <n-button @click="deletCancel">取消</n-button>
      </n-space>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
import { defineComponent, h, reactive, ref, onMounted } from 'vue';
import { useMessage } from 'naive-ui';
import { BasicTable, TableAction } from '@/components/Table';
import { BasicForm, useForm } from '@/components/Formdraw/index';
import { getTableList } from '@/api/table/list';
import { columns } from './cloumns';
import { PlusOutlined } from '@vicons/antd';
import { useRouter } from 'vue-router';
import { getRoleList } from '@/api/role/list';
import { addRoleInfo } from '@/api/role/add';
import { viewRoleInfo } from '@/api/role/view';
import { updateRoleInfo } from '@/api/role/update';
import { deleteRoleInfo } from '@/api/role/delete';
import { distributionRole } from '@/api/role/distribution';
import { getRoleOperationList } from '@/api/operation/roleOperatorLIst';
import formatDate from '@/utils/timestamp';
import { createStorage } from '@/utils/Storage';

const Storage = createStorage({ storage: localStorage });

let authorityJson = Storage.get('OPERATORLIST');
const authority = JSON.parse(authorityJson);

// 表单查询按钮
function handleSubmit(values: Recordable) {
  reloadTable();
}

// 表单重置按钮
function handleReset(values: Recordable) {
  viewListParm.value.name = '';
  viewListParm.value.status = '';
  reloadTable();
}

const viewListParm = ref({
  name: '',
  status: '',
  pageNum: 1,
  pageSize: 10,
});

// 全体角色列表
const loadDataTable = async (res) => {
  viewListParm.value.pageNum = res.page;
  viewListParm.value.pageSize = res.pageSize;
  console.log(res);
  let data = await getRoleList(viewListParm.value);
  data.data.body.list.forEach((val) => {
    val.createdTime = formatDate(new Date(val.createdTime));
    if(val.status == '0'){
       val.status = '启用';
    }else{
       val.status = '禁用';
    }
  });
  let datas = {
    list: data.data.body.list,
    page: res.page,
    pageSize: res.pageSize,
    pageCount: Math.ceil(data.data.body.total / res.pageSize),
  };
  console.log(data);
  console.log(datas);
  return datas;
};

const userStatus = [
  {
    label: '全部状态',
    key: '全部状态',
  },
  {
    label: '已批准',
    key: '已批准',
  },
  {
    label: '已拒绝',
    key: '已拒绝',
  },
  {
    label: '未处理',
    key: '未处理',
  },
];

const roleStatelOptions = [
  {
    value: 0,
    label: '启用',
  },
  {
    value: 1,
    label: '禁用',
  },
];

// 表单输入框和表单验证
const schemas = [
  {
    field: 'name',
    component: 'NInput',
    label: '角色名称：',
    componentProps: {
      placeholder: '请输入角色名称',
      onInput: (e: any) => {
        console.log(e);
        viewListParm.value.name = e;
      },
    },
  },
  {
    field: 'type',
    component: 'NSelect',
    label: '角色状态：',
    componentProps: {
      placeholder: '请选择状态',
      options: [
        {
          label: '启用',
          value: '0',
        },
        {
          label: '禁用',
          value: '1',
        },
      ],
      onUpdateValue: (e: any) => {
        viewListParm.value.status = e;
      },
    },
  },
];

const assignModal = ref(false);
const viewModal = ref(false);
const editModal = ref(false);
const router = useRouter();
const addModal = ref(false);
const formRef: any = ref();
const fromValue = ref();
const message = useMessage();
const actionRef = ref();
const name = ref();
const roleState = ref();
const delModal = ref(false);

// 列表行为
const actionColumn = reactive({
  width: 220,
  title: '操作',
  key: 'action',
  fixed: 'right',
  render(record) {
    return h(TableAction as any, {
      style: 'button',
      actions: [
        {
          label: '编辑',
          text: true,
          color: '#2d8cf0',
          onClick: editInfo.bind(null, record),
          ifShow: () => {
            return authority.includes('role_update');
          },
        },
        {
          label: '查看',
          text: true,
          color: '#2d8cf0',
          onClick: viewInfo.bind(null, record),
          ifShow: () => {
            return authority.includes('role_view');
          },
        },
        {
          label: '分配权限',
          text: true,
          color: '#2d8cf0',
          onClick: assignPermission.bind(null, record),
          ifShow: () => {
            return true;
          },
        },
        {
          label: '删除',
          text: true,
          color: '#ff4949',
          onClick: deletInfo.bind(null, record),
          ifShow: () => {
            return authority.includes('role_delete');
          },
        },
      ],
      select: (key) => {
        message.info(`您点击了，${key} 按钮`);
      },
    });
  },
});

// 表单边距和布局格式
const [register, {}] = useForm({
  gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
  labelWidth: 80,
  schemas,
});

// 添加角色信息
function addInfo(record: Recordable) {
  message.info('点击了添加');
  addModal.value = true;
}

// 添加角色变为响应式
const addRole = ref({
  name: '',
  desc: '',
  code: '',
  status: '',
});

// 添加用户表单验证规则
const rules = {
  name: {
    required: true,
    validator(rule, value) {
      if (!value) {
        return new Error('请输入登录名称');
      } else {
        return true;
      }
    },
    message: '请输入登录名称',
    trigger: 'blur',
  },
  desc: {
    required: true,
    message: '请输入角色描述',
    trigger: 'blur',
  },
  code: {
    required: true,
    message: '请输入角色描述',
    trigger: 'blur',
  },
};

// 确认按钮
const addFrom = async (e) => {
  formRef.value.validate(async (errors) => {
    if (!errors) {
      console.log(addRole.value);
      const roleList = await addRoleInfo(addRole.value).then((res) => {
        console.log(res);
        message.success('添加成功');
        reloadTable();
      });
      addModal.value = false;
    } else {
      message.error('添加失败');
    }
  });
};

// 编辑角色变为响应式
const updateRole = ref({
  name: '',
  desc: '',
  code: '',
  status: '',
});

// 编辑角色信息
async function editInfo(record: Recordable) {
  let roleId = record.roleId;
  let data = await viewRoleInfo({ roleId });
  console.log(data);
  updateRole.value = data.data.body;
  if (updateRole.value.status == '0') {
    updateRole.value.status = '启用';
  }
  if (updateRole.value.status == '1') {
    updateRole.value.status = '禁用';
  }
  message.info('点击了编辑');
  editModal.value = true;
}

// 编辑确认按钮
async function editFrom() {
  if (updateRole.value.status == '启用') {
    updateRole.value.status = '0';
  }
  if (updateRole.value.status == '禁用') {
    updateRole.value.status = '1';
  }
  const data = await updateRoleInfo(updateRole.value).then((res) => {
    console.log(res);
    message.success('添加成功');
    reloadTable();
    editModal.value = false;
  });
}

// 查看角色信息
const viewRole = ref();
async function viewInfo(record: Recordable) {
  console.log('点击了查看', record);
  let roleId = record.roleId;
  let data = await viewRoleInfo({ roleId });
  console.log(data);
  viewRole.value = data.data.body;
  if (viewRole.value.status == '0') {
    viewRole.value.status = '启用';
  }
  if (viewRole.value.status == '1') {
    viewRole.value.status = '禁用';
  }
  viewModal.value = true;
  message.info('点击了查看');
}

// 删除操作
function deletInfo(record: Recordable) {
  console.log('点击了删除', record);
  localStorage.setItem('record', JSON.stringify(record));
  message.info('点击了删除');
  delModal.value = true;
}

// 确认删除
async function deletConfirm() {
  const deleteRole = JSON.parse(localStorage.getItem('record'));
  console.log(deleteRole);
  let { roleId } = deleteRole;
  let data = await deleteRoleInfo({ roleId });
  console.log(data);
  message.success('删除成功');
  delModal.value = false;
  reloadTable();
}

// 取消删除
function deletCancel() {
  message.success('未删除');
  delModal.value = false;
}

const assignInfo = ref();
const assignInfoTree = ref();
const defaultCheckedKeys = ref([]);
const distributionparm = reactive({
  roleCode: '',
  roleOperatorList: [],
});

// 让操作树的值可改变
const updateCheckedKeys = (val) => {
  distributionparm.roleOperatorList = val;
};

// 分配权限
async function assignPermission(record: Recordable) {
  defaultCheckedKeys.value = [];
  distributionparm.roleCode = record.code;
  let roleCode = record.code;
  let data = await getRoleOperationList({ roleCode });
  let dateTree = data.data.body.menuNodes;
  assignInfo.value = dateTree;
  console.log(assignInfo);
  assignInfoTree.value = JSON.parse(
    JSON.stringify(assignInfo.value).replace(/name/g, 'label').replace(/code/g, 'key')
  );
  console.log(assignInfoTree);
  const deleteChildren = (val) => {
    val.map((val) => {
      if (!val.children[0]) {
        delete val.children;
        if (val.checked) {
          console.log(val.checked);
          defaultCheckedKeys.value.push(val.key);
        }
      } else {
        if (val.checked) {
          defaultCheckedKeys.value.push(val.key);
        }
        deleteChildren(val.children);
      }
    });
  };
  deleteChildren(assignInfoTree.value);
  assignModal.value = true;
}

// 确认分配
function assignConfirm() {
  console.log(distributionparm.roleCode);
  console.log(distributionparm.roleOperatorList);
  distributionRole(distributionparm).then((val) => {
    console.log(val);
    assignModal.value = false;
  });
}

// 创建操作树
function createData(level = 3, baseKey = '') {
  if (!level) return undefined;
  return Array.apply(null, { length: 6 - level }).map((_, index) => {
    const key = '' + baseKey + level + index;
    return {
      label: createLabel(level),
      key,
      children: createData(level - 1, key),
    };
  });
}

// 列表刷新
function reloadTable() {
  actionRef.value.reload();
}
</script>

<style lang="less" scoped>
.fromCard {
  margin-top: 12px;
  border: 1px solid rgb(226, 229, 229);
  margin-bottom: 8px;
}
.tableCard {
  border: 1px solid rgb(226, 229, 229);
}
</style>